import DataManager from "./DataManager";
import { ServerAddress } from "./GameConfig";
import SDKUtil, { ApiType } from "./SDK/SDKUtil";

const { ccclass, property } = cc._decorator;

@ccclass
export default class NetUtil {

    protected static _instance: NetUtil = null;
    public static get Instance(): NetUtil {
        if (NetUtil._instance == null) {
            NetUtil._instance = new NetUtil();
        }
        return NetUtil._instance;
    }

    Send(urlData, reqData, succCallback?, failCallback?) {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) { // 接收完毕
                if (xhr.status >= 200 && xhr.status < 400) {// 响应中的数字状态码：表示为有效响应，成功的请求
                    var response = xhr.responseText; // 对文本请求的响应
                    if (response) {
                        console.log("请求" + urlData + "成功,返回数据");
                        var responseJson = JSON.parse(response); // 解析完的json 文件再返回 回调函数
                        console.log(responseJson)
                        if (succCallback) succCallback(responseJson);
                    } else {
                        console.log("无返回数据");
                        if (succCallback) succCallback(false);
                    }
                } else {
                    console.log("请求失败");
                    if (failCallback) failCallback(false);
                }
            }
        };
        let url = ServerAddress + urlData;
        console.log("开始请求,地址 ", url);
        console.log(reqData);
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  //告诉服务器如何解析我的内容
        xhr.setRequestHeader("Content-Type", "json/application");
        xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
        xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST');
        xhr.setRequestHeader('Access-Control-Allow-Headers', 'x-requested-with,content-type');
        xhr.send(JSON.stringify(reqData));
        return;
    }

    sendAccounts(score: number, cb?, fb?) {
        let playerId = DataManager.Instance.getPlayerId();
        if (!playerId) return;
        let videoNum = DataManager.Instance.getVideoNum();
        NetUtil.Instance.Send("/player/settleAccounts", {
            playerId: playerId, integral: score, videoNum: videoNum
        }, (data) => {
            if (data && data.model) DataManager.Instance.setLoginData(data.model);
            if (cb) cb(data);
        }, () => {
            if (fb) fb();
        })
    }

    sendGetGoodsList(cb?, fb?) {
        NetUtil.Instance.Send("/player/goodsList", { playerId: DataManager.Instance.getPlayerId() }, (data) => {
            if (data) DataManager.Instance.setGoodsData(data.model);
            if (cb) cb(data);
        }, () => {
            if (fb) fb();
        })
    }

    sendBuyGoods(goodsId, num: number, account: string, isIos, cb?, fb?) {
        console.log({ goodsId: goodsId, num: num, account: account });
        if (!goodsId || !num || !account) {
            if (fb) fb();
            return;
        }
        let playerId = DataManager.Instance.getPlayerId();
        if (!playerId) return;
        let type = isIos ? 1 : 0;
        NetUtil.Instance.Send("/player/buyGoods", {
            playerId: playerId, goodsId: goodsId, num: num, account: account, userType: type
        }, (data) => {
            if (data && data.model) {
                DataManager.Instance.setLoginData(data.model);
                if (cb) cb(data);
            }
            else {
                if (fb) fb();
            }
        }, () => {
            if (fb) fb();
        })
    }

    sendLogin(cb?, fb?) {
        console.log("开始登陆...");
        SDKUtil.Instance.login((login_data, data) => {
            console.log("和后端连接...", ApiType);
            if (!data) data = { };
            console.log({ code: login_data.code, userinfo: data });
            //微信登录
            if (ApiType == 1) {
                NetUtil.Instance.Send("/player/playerWeChatLogin", {
                    code: login_data.code, userinfo: data.userInfo
                }, (data) => {
                    if (data && data.model) {
                        console.log("登录成功");
                        DataManager.Instance.setLoginData(data.model);
                        console.log(DataManager.Instance.getPlayerId())
                        NetUtil.Instance.sendGetGoodsList();
                        if (cb) cb(data);
                    }
                    else {
                        console.log("登录失败");
                        if (fb) fb();
                    }
                }, () => {
                    console.log("连接失败");
                    if (fb) fb();
                })
            }
            //抖音登录
            else if (ApiType == 2) {

                NetUtil.Instance.Send("/player/playerTikTokLogin", {
                    code: login_data.code, userinfo: data, name: data["nickName"], avatarUrl: data["avatarUrl"]
                }, (data) => {
                    if (data && data.model) {
                        console.log("登录成功");
                        DataManager.Instance.setLoginData(data.model);
                        console.log(DataManager.Instance.getPlayerId())
                        NetUtil.Instance.sendGetGoodsList();
                        if (cb) cb(data);
                    }
                    else {
                        console.log("登录失败");
                        if (fb) fb();
                    }
                }, () => {
                    console.log("连接失败");
                    if (fb) fb();
                })
            }


        });
    }
}